<template>
  <div class="finance-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>{{ club.title }} - 财务管理</h1>
      <el-button type="primary" icon="el-icon-back" @click="goBack">返回</el-button>
    </div>

    <!-- 财务概览卡片 -->
    <el-card class="overview-card">
      <div slot="header" class="card-header">
        <span>财务概览</span>
      </div>
      <div class="overview-content">
        <div class="overview-item">
          <div class="item-value"> {{  formatCurrency(balance["0"])  }}</div>
                  <el-popover
            placement="right"
            trigger="hover"
            width="300"
            popper-class="balance-popover">
              <el-table :data="balanceMap.filter(item => balance[item.value] !== undefined)">
              <el-table-column property="name" label="款项" width="150"></el-table-column>
              <el-table-column prop="value" label="金额" width="120">
                <template slot-scope="scope">
                   {{ formatCurrency(balance[scope.row.value]) }}
                </template>
              </el-table-column>
            </el-table>
            <el-button slot="reference">余额</el-button>
          </el-popover>
        </div>

        <div class="overview-item">
          <div class="item-value">{{ notApprovedRequests }}</div>
          <div class="item-label">待审批申请</div>
        </div>
      </div>
    </el-card>

    <!-- 主要内容区域 -->
    <el-tabs v-model="activeTab" type="border-card" class="finance-tabs">
      <!-- 批款通知标签页 -->
      <el-tab-pane v-if="this.finance"   label="批款通知" name="allocations">
        <div class="tab-header">
          <h3>批款通知列表</h3>
          <el-button type="primary" size="small" icon="el-icon-plus" @click="openActiveRequest()">
            申请批款
          </el-button>
        </div>

        <el-table
          v-loading="allocationsLoading"
          :data="filteredAllocations"
          style="width: 100%"
          border>
          <el-table-column prop="title" label="批款标题" ></el-table-column>
          <el-table-column prop="amount" label="批款金额" >
            <template slot-scope="scope">
              {{ formatCurrency(scope.row.amount) }}
            </template>
          </el-table-column>

          <el-table-column prop="fundType" label="资金类型"  >
            <template slot-scope="scope">
              <el-tag type="primary">
                {{ formatFundType(scope.row.tags) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdTime" label="批款日期" >
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" >
            <template slot-scope="scope">
              <el-button 
                size="mini"
                type="primary"
                @click="showAllocationDetail(scope.row)"
                icon="el-icon-view">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            @current-change="handleAllocationPageChange"
            :current-page.sync="allocationPage"
            :page-size="allocationPageSize"
            layout="total, prev, pager, next"
            :total="totalAllocations">
          </el-pagination>
        </div>
      </el-tab-pane>



      <!-- 交易记录标签页 -->
      <el-tab-pane label="交易记录" name="transactions">
        <div class="tab-header">
          <h3>交易记录</h3>
        </div>

        <el-table
          v-loading="transactionsLoading"
          :data="consumptionItems"
          style="width: 100%"
          border>
          <el-table-column prop="title" width="150"  label="标题" ></el-table-column>
          <el-table-column prop="amount" label="金额" >
            <template slot-scope="scope">
              {{ formatCurrency(scope.row.amount) }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" >
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="stat" label="状态">
            <template slot-scope="scope">
              <el-tag :type="statusConfig.getConsumptionStatusStyle(scope.row.stat)">
                    {{ statusConfig.getConsumptionStatusText(scope.row.stat) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="tags" label="类型">
            <template slot-scope="scope">
              <el-tag >
                    {{ statusConfig.getFundTypes(scope.row.tags) }}
              </el-tag>
            </template>
          </el-table-column>


          <el-table-column  label="操作" >
            <template slot-scope="scope">
              <el-button
                :disabled="!finance"
                size="mini"
                type="primary"
                @click="showTransactionDetail(scope.row)"
                icon="el-icon-view">
                详情
              </el-button>

                <el-button
                v-if="scope.row.stat <= 1"
                size="mini"
                type="success"
                @click="settle(scope.row)"
                icon="el-icon-money">
                结算
                </el-button>


             


                
                
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            @current-change="handleTransactionPageChange"
            :current-page.sync="transactionPage"
            :page-size="transactionPageSize"
            layout="total, prev, pager, next"
            :total="totalTransactions">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>

       <!-- 交易详情对话框 -->
  <el-dialog
    title="交易详情"
    :visible.sync="transactionDetailVisible" 
    width="60%">
    <div v-if="currentTransaction" class="transaction-detail">
      <div class="detail-item">
        <span class="label">标题:</span>
        <span class="value">{{ currentTransaction.title }}</span>
      </div>

      <div class="detail-item">
        <span class="label">活动:</span>
        <span class="value">{{ currentActivity.title }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">描述:</span>
        <span class="value">{{ currentTransaction.description }}</span>
      </div>

      <div class="detail-item">
        <span class="label">金额:</span>
        <span class="value">{{ formatCurrency(currentTransaction.amount) }}</span>
      </div>

      <div class="detail-item">
        <span class="label">创建时间:</span>
        <span class="value">{{ formatDate(currentTransaction.createTime) }}</span>
      </div>
      
      <div class="detail-item">
        <span class="label">状态:</span>
        <span class="value">
          <el-tag :type="statusConfig.getConsumptionStatusStyle(currentTransaction.stat)">
            {{ statusConfig.getConsumptionStatusText(currentTransaction.stat) }}
          </el-tag>
        </span>
      </div>
      
      <div class="detail-item">
        <span class="label">类型:</span>
        <span class="value">
          <el-tag>
            {{ statusConfig.getFundTypes(currentTransaction.tags) }}
          </el-tag>
        </span>
      </div>

      <!-- 当stat=2时显示上传发票部分 -->
      <div v-if="currentTransaction.stat === 2" class="detail-item">
        <span class="label">上传发票:</span>
        <div class="upload-container">
          <el-upload
            class="invoice-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeInvoiceUpload"
            :http-request="uploadInvoiceImage">
            <img v-if="currentTransaction.image" :src="currentTransaction.image" class="invoice-image">
            <i v-else-if="invoiceUploading" class="el-icon-loading"></i>
            <i v-else class="el-icon-plus invoice-uploader-icon"></i>
          </el-upload>
        </div>
      </div>
      
      <!-- 当stat>2时显示已上传的发票 -->
      <div v-else-if="currentTransaction.stat > 2 && currentTransaction.image" class="detail-item">
        <span class="label">发票图片:</span>
        <div class="image-container">
          <el-image 
            :src="currentTransaction.image" 
            class="invoice-preview-image"
            :preview-src-list="[currentTransaction.image]">
          </el-image>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="transactionDetailVisible = false">关闭</el-button>
      <el-button 
        v-if="currentTransaction && currentTransaction.stat === 2" 
        type="primary" 
        @click="saveInvoice"
        :disabled="!currentTransaction.image">
        保存发票
      </el-button>
    </span>
  </el-dialog>




    <!-- 批款详情对话框 -->
        <!-- 批款详情对话框 -->
    <el-dialog
      title="批款详情"
      :visible.sync="allocationDetailVisible"
      width="70%">
      <div v-if="currentAllocation" class="allocation-detail">
        <h3>{{ currentAllocation.title }}</h3>
        <div class="detail-item">
          <span class="label">批款金额:</span>
          <span class="value">{{ formatCurrency(currentAllocation.amount) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">剩余可用:</span>
          <span class="value">{{ formatCurrency(this.surplus) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">资金类型:</span>
          <span class="value">
             <el-tag type="primary">
                {{ formatFundType(currentAllocation.tags) }}
              </el-tag>
          </span>
        </div>
        <div v-if="currentAllocation.fundType === 'restricted'" class="detail-item">
          <span class="label">用途限制:</span>
          <span class="value">{{ currentAllocation.purposeRestriction }}</span>
        </div>
        <div class="detail-item">
          <span class="label">批款日期:</span>
          <span class="value">{{ formatDate(currentAllocation.createTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">批款说明:</span>
          <div class="value description">{{ currentAllocation.description }}</div>
        </div>

        <!-- 添加相关请求列表 -->
        <div class="related-requests-section">
          <h4>相关资金申请</h4>
          <el-table
            v-loading="relatedRequestsLoading"
            :data="relatedRequests"
            style="width: 100%"
            border>
            <el-table-column prop="title" label="申请标题" ></el-table-column>
            <el-table-column prop="requestAmount" label="申请金额" >
              <template slot-scope="scope">
                {{ formatCurrency(scope.row.amount) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.stat)">
                  {{ getStatusText(scope.row.stat) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="requestTime" label="申请日期" >
              <template slot-scope="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="showRequestDetail(scope.row)"
                  icon="el-icon-view">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="relatedRequests.length === 0 && !relatedRequestsLoading" class="empty-data">
            <i class="el-icon-document"></i>
            <p>暂无相关资金申请记录</p>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationDetailVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="applyFunds(currentAllocation)"
          :disabled="!currentAllocation || currentAllocation.remainingAmount <= 0">
          申请使用
        </el-button>
      </span>
    </el-dialog>

    <!-- 申请使用资金对话框 -->
    <el-dialog
      title="申请使用资金"
      :visible.sync="fundRequestDialogVisible"
      width="50%">
      <el-form
        :model="fundRequestForm"
        :rules="fundRequestRules"
        ref="fundRequestForm"
        label-width="100px">
        <el-form-item label="申请标题" prop="title">
          <el-input v-model="fundRequestForm.title" placeholder="请输入申请标题"></el-input>
        </el-form-item>
        <el-form-item label="申请金额" prop="requestAmount">
          <el-input-number
            v-model="fundRequestForm.amount"
            :min="0"
            style="width: 200px">
          </el-input-number>
        </el-form-item>
        <el-form-item label="金额类型" prop="tags">
          <el-select
            v-model="fundRequestForm.tags"
            placeholder="请选择金额类型"
            style="width: 100%"
            clearable>
            <el-option
              v-for="item in fundTypes"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用途说明" prop="purpose">
          <el-input
            type="textarea"
            v-model="fundRequestForm.description"
            placeholder="请详细说明资金用途"
            :rows="4">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="fundRequestDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFundRequest">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 申请批款对话框 -->
    <el-dialog
      title="申请批款"
      :visible.sync="allocationRequestDialogVisible"
      width="50%">
      <el-form
        :model="allocationRequestForm"
        :rules="allocationRequestRules"
        ref="allocationRequestForm"
        label-width="100px">
        <el-form-item label="申请标题" prop="title">
          <el-input v-model="allocationRequestForm.title" placeholder="请输入申请标题"></el-input>
        </el-form-item>
        <el-form-item label="申请金额" prop="requestAmount">
          <el-input-number
            v-model="allocationRequestForm.requestAmount"
            :min="100"
            :precision="2"
            :step="100"
            style="width: 200px">
          </el-input-number>
        </el-form-item>
        <el-form-item label="申请理由" prop="description">
          <el-input
            type="textarea"
            v-model="allocationRequestForm.description"
            placeholder="请详细说明申请批款的理由"
            :rows="4">
          </el-input>
        </el-form-item>
        <el-form-item label="用途说明" prop="purpose">
          <el-input
            type="textarea"
            v-model="allocationRequestForm.purpose"
            placeholder="请详细说明资金用途"
            :rows="3">
          </el-input>
        </el-form-item>
        <el-form-item label="关联活动" prop="activityId">
          <el-select
            v-model="allocationRequestForm.activityId"
            placeholder="请选择关联活动（可选）"
            style="width: 100%"
            clearable>
            <el-option
              v-for="item in clubActivities"
              :key="item.id"
              :label="item.title"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationRequestDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAllocationRequest">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 申请详情对话框 -->
    <el-dialog
      title="申请详情"
      :visible.sync="requestDetailVisible"
      width="50%">
      <div v-if="currentRequest" class="request-detail">
        <h3>{{ currentRequest.title }}</h3>
        <div class="detail-item">
          <span class="label">申请金额:</span>
          <span class="value">{{ formatCurrency(currentRequest.requestAmount) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">申请状态:</span>
          <span class="value">
            <el-tag :type="getStatusType(currentRequest.status)">
              {{ getStatusText(currentRequest.status) }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item">
          <span class="label">申请日期:</span>
          <span class="value">{{ formatDate(currentRequest.requestTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">用途说明:</span>
          <div class="value description">{{ currentRequest.purpose }}</div>
        </div>
        <div v-if="currentRequest.status === 'rejected'" class="detail-item">
          <span class="label">拒绝理由:</span>
          <div class="value description">{{ currentRequest.rejectionReason }}</div>
        </div>
        <div v-if="currentRequest.status === 'approved' || currentRequest.status === 'transferred'" class="detail-item">
          <span class="label">审批日期:</span>
          <span class="value">{{ formatDate(currentRequest.approvalDate) }}</span>
        </div>
        <div v-if="currentRequest.status === 'transferred'" class="detail-item">
          <span class="label">打款日期:</span>
          <span class="value">{{ formatDate(currentRequest.transferDate) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">关联批款:</span>
          <span class="value">{{ getAllocationTitle(currentRequest.allocationId) }}</span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="requestDetailVisible = false">关闭</el-button>
        <el-button
          v-if="currentRequest && currentRequest.status === 'approved'"
          type="success"
          @click="uploadInvoice(currentRequest)">
          上传发票
        </el-button>
      </span>
    </el-dialog>

    

    
  </div>
</template>
<script>
import { checkPermission, formatCurrency, formatDate } from '@/utils/filters';
import httpInstance from '@/utils/http';
import { statusConfig } from '@/utils/status';
export default {
  name: 'ClubFinance',
  data() {
    return {
      // 资金类型
      fundTypes : [
            { name: '设备购置资金', value: '1' },
            { name: '宣传推广资金', value: '2' },
            { name: '学术研究资金', value: '3' },
            { name: '衣食住行资金', value: '4' },
            { name: '比赛活动资金', value: '5' },
        ],
      finance:false,
      // 用户信息
      user: JSON.stringify(localStorage.getItem('user')),
      // 当前活动信息
      currentActivity: null,
      // 消费项详情dialog展示属性
      transactionDetailVisible: false,
       statusConfig: statusConfig, // 确保在 data 中声明
      // 消费项列表
      consumptionItems: [],
      // 发票上传状态
      invoiceUploading: false,
      // 未处理申请数量
      notApprovedRequests: 0,
      // 社团金额信息
      balance: {},
      // 社团信息
      club: {
        id: null,
        title: '加载中...'
      },
      balanceMap: {},

      // 社团账户信息
      clubAccount: {
        totalBalance: 0,
        availableBalance: 0
      },
      

      // 当前激活的标签页
      activeTab: 'allocations',

      // 批款通知相关
      allocations: [],
      allocationsLoading: true,
      allocationPage: 1,
      allocationPageSize: 10,
      totalAllocations: 0,

      // 资金申请相关
      requests: [],
      requestsLoading: true,
      requestPage: 1,
      requestPageSize: 10,
      totalRequests: 0,

      // 发票记录相关
      invoices: [],
      invoicesLoading: true,
      invoicePage: 1,
      invoicePageSize: 10,
      totalInvoices: 0,

      // 交易记录相关
      transactions: [],
      transactionsLoading: true,
      transactionPage: 1,
      transactionPageSize: 10,
      totalTransactions: 0,

      // 批款详情对话框
      allocationDetailVisible: false,
      currentAllocation: null,
      surplus:0,
      relatedRequests: [], // 添加相关请求列表
      relatedRequestsLoading: false, // 添加相关请求加载状态

      // 申请使用资金对话框
      fundRequestDialogVisible: false,
      fundRequestForm: {
        allocationNoticeId: null,
        title: '',
        clubId: null,
        amount: 0,
        description: '',
        tags:'',
        stat:1
      },
      fundRequestRules: {
        allocationId: [{ required: true, message: '请选择批款通知', trigger: 'change' }],
        title: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入申请金额', trigger: 'blur' }],
        description: [{ required: true, message: '请输入用途说明', trigger: 'blur' }]
      },
      selectedAllocationAmount: 0,

      // 申请批款对话框
      allocationRequestDialogVisible: false,
      allocationRequestForm: {
        title: '',
        requestAmount: 1000,
        description: '',
        purpose: '',
        activityId: null
      },
      allocationRequestRules: {
        title: [{ required: true, message: '请输入申请标题', trigger: 'blur' }],
        requestAmount: [{ required: true, message: '请输入申请金额', trigger: 'blur' }],
        description: [{ required: true, message: '请输入申请理由', trigger: 'blur' }],
        purpose: [{ required: true, message: '请输入用途说明', trigger: 'blur' }]
      },

      // 申请详情对话框
      requestDetailVisible: false,
      currentRequest: null,

      // 上传发票对话框
      invoiceDialogVisible: false,
      invoiceForm: {
        requestId: null,
        invoiceNumber: '',
        invoiceAmount: 0,
        invoiceDate: '',
        vendorName: '',
        description: '',
        fileUrl: ''
      },
      invoiceRules: {
        invoiceNumber: [{ required: true, message: '请输入发票编号', trigger: 'blur' }],
        invoiceAmount: [{ required: true, message: '请输入发票金额', trigger: 'blur' }],
        invoiceDate: [{ required: true, message: '请选择发票日期', trigger: 'change' }],
        vendorName: [{ required: true, message: '请输入商家名称', trigger: 'blur' }],
        fileUrl: [{ required: true, message: '请上传发票图片', trigger: 'change' }]
      },

      // 查看发票对话框
      invoiceViewDialogVisible: false,
      currentInvoice: null,

      // 社团活动列表
      clubActivities: []
    };
  },
  computed: {
    // 获取可用的批款通知列表（剩余金额大于0）
    availableAllocations() {
      return this.allocations.filter(item => item.remainingAmount > 0);
    },

    // 待使用的批款通知
    pendingAllocations() {
      return this.allocations.filter(item => item.remainingAmount > 0);
    },

    // 待审批的申请
    pendingRequests() {
      return this.requests.filter(item => item.status === 'pending');
    },

    // 分页后的批款通知
    filteredAllocations() {
      const start = (this.allocationPage - 1) * this.allocationPageSize;
      const end = start + this.allocationPageSize;
      return this.allocations.slice(start, end);
    },

    // 分页后的资金申请
    filteredRequests() {
      const start = (this.requestPage - 1) * this.requestPageSize;
      const end = start + this.requestPageSize;
      return this.requests.slice(start, end);
    },

    // 分页后的发票记录
    filteredInvoices() {
      const start = (this.invoicePage - 1) * this.invoicePageSize;
      const end = start + this.invoicePageSize;
      return this.invoices.slice(start, end);
    },

    // 分页后的交易记录
    filteredTransactions() {
      const start = (this.transactionPage - 1) * this.transactionPageSize;
      const end = start + this.transactionPageSize;
      return this.transactions.slice(start, end);
    }
  },
  created() {
    // 获取路由参数中的社团ID
    const clubId = this.$route.params.id;
    if (clubId) {
      this.club.id = clubId;
      this.fetchClubInfo();
      this.fetchClubAccount();
      this.fetchAllocations(); // 获取批款通知
      this.fetchRequests();
      this.fetchInvoices();
      this.fetchTransactions();
      this.fetchClubActivities();
      this.fetchClubAccount()
      this.fetchConsumptionItems();
      this.fetchRequestCountByStat(1) // 1 未处理 2 已处理 3 已拒绝 4 已打款 5 已失效
      // 把user转为可用的对象
      let user = JSON.parse(localStorage.getItem('user'))
      this.checkPermission(user.id, clubId)
     
    } else {
      this.$message.error('社团ID不存在,请返回重试');
      this.goBack();
    }
  },
  methods: {
    // 主动申请页面
    openActiveRequest() {
      this.fundRequestForm = {
        allocationNoticeId: null,
        title: '',
        amount: 0,
        description: '',
        tags:'',
        stat:1
      };
      this.fundRequestDialogVisible = true;
    },


    // 获取当前用户是否有权力管理财务
    async checkPermission(userId, clubId) {
    try {
        const res = await httpInstance.post(`/api/club/select/${userId}/${clubId}/finance`)
      if (res.code === 200) {
        this.finance = res.data      
        this.activeTab = this.finance ? 'allocations' : 'transactions';
      }
    } catch (error) {
        console.error('权限检查失败:', error);
    }
  },


    // 发票上传前的验证
  beforeInvoiceUpload(file) {
    const isImage = file.type.startsWith('image/');
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isImage) {
      this.$message.error('上传发票只能是图片格式!');
      return false;
    }
    if (!isLt2M) {
      this.$message.error('上传发票图片大小不能超过 2MB!');
      return false;
    }
    return true;
    },

    // 处理发票上传
  uploadInvoiceImage(options) {
    const file = options.file;
    const formData = new FormData();
    formData.append('file', file);

    this.invoiceUploading = true;

    httpInstance.post('/api/sys/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(response => {
      if (response.code === 200) {
        this.currentTransaction.image = response.data;
        this.$message.success('发票上传成功');
      } else {
        this.$message.error(response.msg || '发票上传失败');
      }
    }).catch(error => {
      console.error('发票上传失败:', error);
      this.$message.error('发票上传失败，请稍后重试');
    }).finally(() => {
      this.invoiceUploading = false;
    });
  },
    // 结算消费项
    settle(row) {
      this.$confirm("确定要结算该消费项吗？")
      .then(() => {
        httpInstance({
          url: `/api/consumption/settle`,
          data: row,
          method:'post'
      }).then(response => {
          if (response.code === 200) {
            this.$message.success('结算成功');
            this.fetchConsumptionItems();
            this.fetchClubAccount();
          } else {
            this.$message.error(response.msg || '结算失败');
          }
        })
        .catch(error => {
          console.error('结算失败:', error);
          this.$message.error('结算失败，请稍后重试');
        });
      }).catch(error => {
        console.log("结算取消");
      })
    },
    // 根据活动id 获取活动的信息
    async fetchActivityDetail(activityId) {
      const res = await httpInstance.get("/api/activity/" + activityId);
      if (res.code === 200) {
        this.currentActivity = res.data;
      }
    },

    // 展示消费项详情对话框
    showTransactionDetail(row) {
      this.currentTransaction = row;
      // 根据actibityId 获取该消费项的活动信息
      this.fetchActivityDetail(row.activityId)
      this.transactionDetailVisible = true;
    },


    // 消费项列表
    fetchConsumptionItems() {
      httpInstance.post('/api/consumption/listByClubId/' + this.club.id)
        .then(response => {
          if (response.code === 200) {
            this.consumptionItems = response.data;
          } else {
            this.$message.error('获取消费项列表失败');
          }
        })
        .catch(error => {
          console.error('获取消费项列表失败:', error);
          this.$message.error('获取消费项列表失败，请稍后重试');
        });
    },
    // 获取 社团为处理的批款申请
    async fetchRequestCountByStat(stat) {
      const res = await httpInstance.post(`/api/finance/getRequestNumByStat/${this.club.id}/${stat}`);
      this.notApprovedRequests = res.data;
      console.log("未处理申请", this.notApprovedRequests)
    },


    // 批款通知类型
    formatFundType(type) {
       // 资金类型
      const fundTypes =  {
        '1': '设备购置资金',
        '2': '宣传推广资金',
        '3': '学术研究资金',
        '4': '衣食住行资金',
        '5':'比赛活动资金',
      }
      return fundTypes[type] || '';
    },

    // 获取本社团的balance
    async fetchClubAccount() {
      const res = await httpInstance.post(`/api/finance/totalBalance/${this.club.id}`);
      if (res.code === 200) {
        this.balance = res.data
        console.log(this.balancec)
      }

      // 获取balance 的map
      const res2 = await httpInstance.post(`/api/sys/fundTypes`);
      if(res2.code === 200) {
        this.balanceMap = res2.data
      }
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 获取社团基本信息
    async fetchClubInfo() {
      // try {
      //   const res = await httpInstance.get(`/api/club/detail?id=${this.club.id}`);
      //   if (res.code === 200) {
      //     this.club = res.data;
      //   } else {
      //     // this.$message.error(res.message || '获取社团信息失败');
      //   }
      // } catch (error) {
      //   // console.error('获取社团信息失败:', error);
      //   // this.$message.error('获取社团信息失败，请稍后重试');
      // }
    },

    //

    // 获取批款通知列表
    async fetchAllocations() {
      this.allocationsLoading = true;
      try {
        const res = await httpInstance.post(`/api/finance/getNoticeByClubId/${this.club.id}`);
        if (res.code === 200) {
          this.allocations = res.data || [];
          this.totalAllocations = this.allocations.length;

        } else {
          this.$message.error(res.message || '获取批款通知失败');
        }
      } catch (error) {
        console.error('获取批款通知失败:', error);
        this.$message.error('获取批款通知失败，请稍后重试');
      } finally {
        this.allocationsLoading = false;
      }
    },

    // 获取资金申请列表
    async fetchRequests() {
      // this.requestsLoading = true;
      // try {
      //   const res = await httpInstance.get(`/api/finance/requests?clubId=${this.club.id}`);
      //   if (res.code === 200) {
      //     this.requests = res.data || [];
      //     this.totalRequests = this.requests.length;
      //   } else {
      //     // this.$message.error(res.message || '获取资金申请失败');
      //   }
      // } catch (error) {
      //   console.error('获取资金申请失败:', error);
      //   // this.$message.error('获取资金申请失败，请稍后重试');
      // } finally {
      //   this.requestsLoading = false;
      // }
    },

    // 获取发票记录列表
    async fetchInvoices() {
      // this.invoicesLoading = true;
      // try {
      //   const res = await httpInstance.get(`/api/finance/invoices?clubId=${this.club.id}`);
      //   if (res.code === 200) {
      //     this.invoices = res.data || [];
      //     this.totalInvoices = this.invoices.length;
      //   } else {
      //     // this.$message.error(res.message || '获取发票记录失败');
      //   }
      // } catch (error) {
      //   console.error('获取发票记录失败:', error);
      //   // this.$message.error('获取发票记录失败，请稍后重试');
      // } finally {
      //   this.invoicesLoading = false;
      // }
    },

    // 获取交易记录列表
    async fetchTransactions() {
      this.transactionsLoading = true;
      try {
        const res = await httpInstance.get(`/api/finance/transactions?clubId=${this.club.id}`);
        if (res.code === 200) {
          this.transactions = res.data || [];
          this.totalTransactions = this.transactions.length;
        } else {
          // this.$message.error(res.message || '获取交易记录失败');
        }
      } catch (error) {
        console.error('获取交易记录失败:', error);
        // this.$message.error('获取交易记录失败，请稍后重试');
      } finally {
        this.transactionsLoading = false;
      }
    },

    // 获取社团活动列表
    async fetchClubActivities() {
      try {
        const res = await httpInstance.get(`/api/activity/club?clubId=${this.club.id}`);
        if (res.code === 200) {
          this.clubActivities = res.data || [];
        } else {
          console.error('获取社团活动列表失败:', res.message);
        }
      } catch (error) {
        console.error('获取社团活动列表失败:', error);
      }
    },

        // 显示批款详情
    showAllocationDetail(allocation) {
      this.currentAllocation = allocation;
      this.allocationDetailVisible = true;
      this.relatedRequests = []; // 清空之前的相关请求
      this.fetchRelatedRequests(allocation.id); // 获取相关请求
    },

    // 获取批款通知相关的请求
    async fetchRelatedRequests(noticeId) {
      this.relatedRequestsLoading = true;
      try {
        const res = await httpInstance.post(`/api/finance/getRequestByNoticeId/${noticeId}`);
        if (res.code === 200) {
          this.relatedRequests = res.data || [];
          this.surplus = this.currentAllocation.amount
          for (let i = 0; i < this.relatedRequests.length; i++){
            this.surplus -= this.relatedRequests[i].amount
          }
        } else {
          this.$message.warning(res.message || '获取相关申请记录失败');
        }
      } catch (error) {
        console.error('获取批款通知相关请求失败:', error);
        this.$message.warning('获取相关申请记录失败，请稍后重试');
      } finally {
        this.relatedRequestsLoading = false;
      }
    },

    // 申请使用资金
    applyFunds(allocation) {
      this.fundRequestForm = {
        allocationNoticeId: allocation.id,
        title: '',
        amount: 0,
        description: '',
        tags:this.currentAllocation.tags,
        stat:1
      };
      this.selectedAllocationAmount = allocation.remainingAmount;
      this.fundRequestDialogVisible = true;
    },

    // 处理批款选择变化
    handleAllocationChange(allocationId) {
      const allocation = this.allocations.find(item => item.id === allocationId);
      if (allocation) {
        this.selectedAllocationAmount = allocation.remainingAmount;
        // 如果当前输入的金额超过了可用金额，则调整为可用金额
        if (this.fundRequestForm.requestAmount > allocation.remainingAmount) {
          this.fundRequestForm.requestAmount = allocation.remainingAmount;
        }
      }
    },

    // 提交资金申请
    submitFundRequest() {
      this.$refs.fundRequestForm.validate(async valid => {
        if (valid) {
          this.fundRequestForm.amount *= 100
          try {
            if(this.fundRequestForm.amount > this.surplus && this.allocationDetailVisible){
              this.$message.warning('申请金额不能大于批款金额')
              return
            }
            this.fundRequestForm.clubId = this.club.id  
            const res = await httpInstance.post('/api/finance/create_request', this.fundRequestForm);
            if (res.code === 200) {
              this.$message.success('资金申请提交成功');
              this.fundRequestDialogVisible = false;
              // 刷新数据
              this.fetchAllocations();
              this.fetchRequests();
            } else {
              this.$message.error(res.message || '提交失败');
            }
          } catch (error) {
            console.error('提交资金申请失败:', error);
            this.$message.error('提交资金申请失败，请稍后重试');
          }
        }
      });
    },

    // 显示申请批款对话框
    showAllocationRequestDialog() {
      this.allocationRequestForm = {
        title: '',
        requestAmount: 1000,
        description: '',
        purpose: '',
        activityId: null
      };
      this.allocationRequestDialogVisible = true;
    },

    // 提交批款申请
    submitAllocationRequest() {
      this.$refs.allocationRequestForm.validate(async valid => {
        if (valid) {
          try {
            const requestData = {
              ...this.allocationRequestForm,
              clubId: this.club.id
            };

            const res = await httpInstance.post('/api/finance/allocation/request', requestData);
            if (res.code === 200) {
              this.$message.success('批款申请提交成功');
              this.allocationRequestDialogVisible = false;
            } else {
              this.$message.error(res.message || '提交失败');
            }
          } catch (error) {
            console.error('提交批款申请失败:', error);
            this.$message.error('提交批款申请失败，请稍后重试');
          }
        }
      });
    },

    // 显示申请详情
    showRequestDetail(request) {
      this.currentRequest = request;
      this.requestDetailVisible = true;
    },

    // 上传发票
    uploadInvoice(request) {
      this.invoiceForm = {
        requestId: request.id,
        invoiceNumber: '',
        invoiceAmount: request.requestAmount,
        invoiceDate: new Date(),
        vendorName: '',
        description: '',
        fileUrl: ''
      };
      this.invoiceDialogVisible = true;
    },

    // 发票文件上传前检查
    beforeInvoiceUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('发票图片只能是JPG或PNG格式!');
        return false;
      }

      if (!isLt5M) {
        this.$message.error('发票图片大小不能超过5MB!');
        return false;
      }

      return true;
    },

    // 上传发票文件
    async uploadInvoiceFile(options) {
      const file = options.file;
      try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);

        const res = await httpInstance.post('/api/upload/image', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (res.code === 200) {
          this.invoiceForm.fileUrl = res.data;
          this.$message.success('发票图片上传成功');
        } else {
          this.$message.error(res.message || '上传失败');
        }
      } catch (error) {
        console.error('上传发票图片失败:', error);
        this.$message.error('上传发票图片失败，请稍后重试');
      }
    },

    // // 提交发票
    // submitInvoice() {
    //   this.$refs.invoiceForm.validate(async valid => {
    //     if (valid) {
    //       try {
    //         const res = await httpInstance.post('/api/finance/invoice/create', this.invoiceForm);
    //         if (res.code === 200) {
    //           this.$message.success('发票提交成功');
    //           this.invoiceDialogVisible = false;
    //           // 刷新数据
    //           this.fetchInvoices();
    //           this.fetchRequests();
    //         } else {
    //           this.$message.error(res.message || '提交失败');
    //         }
    //       } catch (error) {
    //         console.error('提交发票失败:', error);
    //         this.$message.error('提交发票失败，请稍后重试');
    //       }
    //     }
    //   });
    // },

    // 查看发票
    viewInvoice(invoice) {
      this.currentInvoice = invoice;
      this.invoiceViewDialogVisible = true;
    },

    // 预览发票大图
    previewInvoiceImage() {
      if (this.currentInvoice && this.currentInvoice.fileUrl) {
        // 使用Element UI的图片预览功能
        const h = this.$createElement;
        this.$msgbox({
          title: '发票图片',
          message: h('img', {
            attrs: {
              src: this.currentInvoice.fileUrl,
              style: 'width: 100%'
            }
          }),
          showCancelButton: false,
          confirmButtonText: '关闭'
        });
      }
    },

    // 获取批款通知标题
    getAllocationTitle(allocationId) {
      const allocation = this.allocations.find(item => item.id === allocationId);
      return allocation ? allocation.title : '未知批款';
    },

    // 处理批款分页变化
    handleAllocationPageChange(page) {
      this.allocationPage = page;
    },

    // 处理申请分页变化
    handleRequestPageChange(page) {
      this.requestPage = page;
    },

    // 处理发票分页变化
    handleInvoicePageChange(page) {
      this.invoicePage = page;
    },

    // 处理交易记录分页变化
    handleTransactionPageChange(page) {
      this.transactionPage = page;
    },

    // 格式化金额
    formatCurrency(amount) {
      return '¥ ' + parseFloat(amount / 100).toFixed(2);
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知日期';
      const date = new Date(dateStr);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    },

    // 获取申请状态对应的类型
    // 获取申请状态对应的类型
    getStatusType(status) {
      const statusMap = {
        1: 'warning',   // 申请中
        2: 'primary',   // 已打款
        3: 'success'    // 已上传发票
      };
      return statusMap[status] || 'info';
    },

     // 获取申请状态对应的文本
    getStatusText(status) {
      const statusMap = {
        1: '申请中',
        2: '已打款',
        3: '已上传发票'
      };
      return statusMap[status] || '未知状态';
    },

    // 获取发票状态对应的类型
    getInvoiceStatusType(status) {
      const statusMap = {
        'uploaded': 'warning',
        'verified': 'success',
        'rejected': 'danger'
      };
      return statusMap[status] || 'info';
    },

    // 获取发票状态对应的文本
    getInvoiceStatusText(status) {
      const statusMap = {
        'uploaded': '已上传',
        'verified': '已审核',
        'rejected': '有问题'
      };
      return statusMap[status] || '未知状态';
    },

    // 保存发票信息
    saveInvoice() {
      if (!this.currentTransaction.image) {
        this.$message.warning('请先上传发票图片');
        return;
      }

      // 构建请求参数
      const updateData = {
        id: this.currentTransaction.id,
        image: this.currentTransaction.image,
        stat: 3 // 更新为已上传发票状态
      };
      
      // 调用更新接口
      httpInstance.post('/api/consumption/update', updateData)
        .then(response => {
          if (response.code === 200) {
            this.$message.success('发票保存成功');
            this.transactionDetailVisible = false;
            this.fetchConsumptionItems(); // 刷新交易列表
            this.fetchClubAccount(); // 刷新账户余额
          } else {
            this.$message.error(response.msg || '发票保存失败');
          }
        })
        .catch(error => {
          console.error('发票保存失败:', error);
          this.$message.error('发票保存失败，请稍后重试');
        });
    }
  }
};
</script>

<style scoped>

/* 发票上传样式 */
.invoice-uploader {
  border: 2px dashed #e0e0e0;
  border-radius: 12px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
  max-width: 400px;
  height: 225px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.invoice-uploader:hover {
  border-color: #4b6cb7;
  box-shadow: 0 0 10px rgba(75, 108, 183, 0.2);
}

.invoice-uploader-icon {
  font-size: 32px;
  color: #c0c4cc;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.invoice-image {
  width: 100%;
  height: 225px;
  display: block;
  object-fit: cover;
  border-radius: 10px;
}

:deep(.el-upload__tip) {
  font-size: 13px;
  color: #909399;
  margin-top: 10px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.finance-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.overview-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overview-content {
  display: flex;
  justify-content: space-around;
  padding: 20px 0;
}

.overview-item {
  text-align: center;
  padding: 0 15px;
}

.item-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.item-label {
  font-size: 14px;
  color: #606266;
}

.finance-tabs {
  margin-top: 20px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.tab-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.allocation-detail,
.request-detail {
  padding: 10px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
}

.detail-item .label {
  width: 100px;
  font-weight: bold;
  color: #606266;
}

.detail-item .value {
  flex: 1;
}

.detail-item .description {
  white-space: pre-line;
  color: #606266;
}

.amount-hint {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}

.invoice-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: inline-block;
}

.invoice-uploader:hover {
  border-color: #409EFF;
}

.invoice-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.invoice-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.invoice-view {
  display: flex;
  flex-wrap: wrap;
}

.invoice-info {
  flex: 1;
  min-width: 300px;
}

.invoice-image-container {
  flex: 1;
  min-width: 300px;
  text-align: center;
}

.invoice-detail-image {
  max-width: 100%;
  max-height: 400px;
  cursor: pointer;
}

.image-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.income-amount {
  color: #67C23A;
  font-weight: bold;
}

.expense-amount {
  color: #F56C6C;
  font-weight: bold;
}

/* ... 现有的样式 */

.related-requests-section {
  /* width: 800px; */
  width: 100%; /* 将注释掉的width: 800px改为100% */
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}
.allocation-detail {
  width: 100%;
  max-width: 10px 20px;
}

.related-requests-section h4 {
  margin-bottom: 15px;
  font-size: 16px;
  color: #303133;
}

.empty-data {
  text-align: center;
  padding: 20px 0;
  color: #909399;
}

.empty-data i {
  font-size: 32px;
  margin-bottom: 10px;
}

.empty-data p {
  margin: 0;
  font-size: 14px;
}
.balance-popover {
  min-width: 300px;
}

/* 确保表格内容不会被截断 */
:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

/* 发票预览图片样式 */
.invoice-preview-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  cursor: zoom-in;
}

.image-container {
  margin-top: 8px;
}

</style>
